package com.auxgroup.smarthome.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件类工具
 * Created by lixiaoxiao on 18-4-2.
 */
public class FileUtils {
    public static void writeFile(String fileName,String content){
        FileWriter fw = null;
        BufferedWriter bfw = null;
        Path fpath=Paths.get(fileName);
        //创建文件
        if(!Files.exists(fpath)) {
            try {
                Files.createFile(fpath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //创建BufferedWriter
        try {
            fw = new FileWriter(fileName,true);
            bfw = new BufferedWriter(fw);
            bfw.write(content);
        } catch (IOException e) {
            throw new RuntimeException("文件写入失败");
        }finally {
            try{
                if(bfw != null) {
                    bfw.flush();
                    bfw.close();
                }
            }catch (IOException e){
                throw new RuntimeException("文件流关闭失败");
            }
            try {
                if(fw != null){
                    fw.close();
                }
            }catch (IOException e){
                throw new RuntimeException("文件流关闭失败");
            }
        }

    }
}
